<template>
  <h-drawer
    v-model="visible"
    title="创建条码"
    :width="60"
    :loading="saveLoading || getDepartmentOptionsLoading"
    @close="onClose"
  >
    <div class="create_code">
      <el-form ref="ruleFormRef" :rules="rules" :model="createCode" inline-message>
        <el-form-item required label="批次名称" prop="name">
          <el-input
            v-model.trim="createCode.name"
            maxlength="10"
            placeholder="请输入批次名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="所属部门" prop="departmentIds">
          <el-select
            v-model="createCode.departmentIds"
            placeholer="请选择所属部门"
            multiple
            style="width: 180px"
          >
            <el-option
              v-for="(option, optionIndex) in departmentOptions"
              :key="optionIndex"
              :label="option.name"
              :value="option.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="总条码数量:">
          <div class="num">{{ (createCode.qty = num) }}</div>
        </el-form-item>
      </el-form>
      <div class="table_container">
        <div class="title">
          <div class="left">创建条码清单</div>
          <div class="right">可批量创建产品条码</div>
        </div>
        <div class="table">
          <el-table :border="true" stripe :data="createCode.codeVos" height="100%">
            <el-table-column label="产品型号">
              <template #default="scope">
                <el-select
                  v-model="scope.row.goodsId"
                  class="part"
                  :filter-method="remoteMethod"
                  :loading="loading2"
                  remote-show-suffix
                  placeholder="型号"
                  filterable
                  clearable
                  @focus="focusIndex(scope.$index)"
                  @change="chaneSelect(scope.$index, scope.row.goodsId, '')"
                >
                  <el-option
                    v-for="item in scope.row.options"
                    :key="item.id"
                    :value="item.id"
                    :label="item.model"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="产品规格">
              <template #default="scope">
                <el-select
                  v-model="scope.row.goodsSpecId"
                  class="part"
                  :loading="loading3"
                  remote-show-suffix
                  :filter-method="remoteMethod3"
                  placeholder="规格"
                  filterable
                  clearable
                >
                  <el-option
                    v-for="item in scope.row.options2"
                    :key="item.id"
                    :value="item.id"
                    :label="item.name"
                    @click="changegoodsSpec(scope.row, item)"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="条码数量">
              <template #default="scope">
                <el-input
                  v-model.trim="scope.row.qty"
                  class="num-inp"
                  @input="scope.row.qty = scope.row.qty.replace(/[^0-9]/g, '')"
                />
              </template>
            </el-table-column>
            <el-table-column label="质保周期">
              <template #default="scope">
                <el-input
                  v-model.trim="scope.row.warrantyDay"
                  class="num-inp"
                  @input="scope.row.warrantyDay = scope.row.warrantyDay.replace(/[^0-9]/g, '')"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template #default="scope">
                <el-space :size="0" :spacer="spacer">
                  <HLink
                    v-if="createCode.codeVos.length > 1"
                    type="error"
                    @click="deleteType(scope.$index)"
                    >删除</HLink
                  >
                  <h-link v-if="scope.$index === 0" @click="addTypes">添加</h-link>
                </el-space>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <template #footer>
      <HButton is-modal type="primary" @click="onaddSave(ruleFormRef)">保存</HButton>
      <HButton is-modal @click="onClose">取消</HButton>
    </template>
  </h-drawer>
</template>

<script setup lang="ts">
  import { reactive, computed, ref, onMounted, watch, h } from 'vue'
  import {
    productPageSelect,
    productSpecPageSelect,
    sparePageSelect,
    spareSpecPageSelect,
    addSave,
  } from '@/api/code'
  import { ElDivider, ElMessage } from 'element-plus'
  import type { FormInstance } from 'element-plus'
  import * as _ from 'lodash'
  import { useGetDepartmentOptions } from '@/services/module/department/useOptions'

  const {
    options: departmentOptions,
    getOptionsLoading: getDepartmentOptionsLoading,
    getOptions: getDepartmentOptions,
  } = useGetDepartmentOptions()

  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: () => false,
    },
  })

  const emits = defineEmits<{
    (e: 'update:modelValue', value: boolean): void
    (e: 'update'): void
  }>()

  // 间距组件的间隔符
  const spacer = h(ElDivider, {
    direction: 'vertical',
    style: 'display: flex; align-items: center;',
  })
  const changegoodsSpec = (item, item2) => {
    item.warrantyDay = item2.warrantyDay
  }
  const options = ref(null)
  const options2 = ref(null)
  const loading2 = ref(true)
  const loading3 = ref(false)
  const optId2 = ref()
  const optIndex = ref()
  const opt2Index = ref()
  const ruleFormRef = ref()

  const rules = reactive({
    name: [{ required: true, message: '请输入批次名称', trigger: 'blur' }],
  })
  const createCode = reactive({
    codeVos: [
      {
        goodsId: null, //产品ID
        goodsSpecId: null, //产品规格ID
        qty: '1', //生成条码数量
        warrantyDay: ' 1', //质保周期/天数
        options: [],
        options2: [],
      },
    ],
    name: '', //批次名称
    qty: 1, //条码数量
    type: 1, //条码类型：1-成品、2-物料
    departmentIds: [],
  })

  const num = computed(() => {
    let coun = 0
    createCode.codeVos.filter((o) => {
      coun += parseInt(o.qty)
    })
    return coun
  })
  // 增加型号
  const addTypes = () => {
    let tmp = {
      goodsId: null, //产品ID
      goodsSpecId: null, //产品规格ID
      qty: ' 1', //生成条码数量
      warrantyDay: '1', //质保周期/天数
      options: options.value,
      options2: null,
    }
    createCode.codeVos.push(tmp)
  }
  // 删除型号
  const deleteType = (val) => {
    createCode.codeVos = createCode.codeVos.filter((o, index) => index != val)
  }
  const focusIndex = (val) => {
    opt2Index.value = val
  }
  const remoteMethod = _.throttle((val: string) => {
    let data = {
      limit: 0,
      name: val,
      page: 0,
    }
    if (createCode.type == 1) {
      productPageSelect(data).then((res) => {
        if (res.data.code == 20000) {
          options.value = res.data.data.rows
          loading2.value = false
          createCode.codeVos[opt2Index.value].options = options.value
        } else {
          ElMessage({
            showClose: true,
            message: res.data.message,
            type: 'error',
            duration: 5000,
            plain: true,
          })
        }
      })
    } else {
      sparePageSelect(data).then((res) => {
        if (res.data.code == 20000) {
          options.value = res.data.data.rows
          loading2.value = false
          createCode.codeVos[opt2Index.value].options = options.value
        } else {
          ElMessage({
            showClose: true,
            message: res.data.message,
            type: 'error',
            duration: 5000,
            plain: true,
          })
        }
      })
    }
  }, 500)
  const remoteMethod3 = _.throttle((val: string) => {
    if (val) {
      createCode.codeVos[optIndex.value].options2 = null
    }
    let data = {
      limit: 0,
      name: val,
      page: 0,
    }
    if (!optId2.value) {
      return
    }
    if (createCode.type == 1) {
      productSpecPageSelect(data, optId2.value).then((res) => {
        if (res.data.code == 20000) {
          options2.value = res.data.data.rows
          createCode.codeVos[optIndex.value].options2 = options2.value
        } else {
          ElMessage({
            showClose: true,
            message: res.data.message,
            type: 'error',
            duration: 5000,
            plain: true,
          })
        }
        loading3.value = false
      })
    } else {
      spareSpecPageSelect(data, optId2.value).then((res) => {
        if (res.data.code == 20000) {
          options2.value = res.data.data.rows
          createCode.codeVos[optIndex.value].options2 = options2.value
        } else {
          ElMessage({
            showClose: true,
            message: res.data.message,
            type: 'error',
            duration: 5000,
            plain: true,
          })
        }
        loading3.value = false
      })
    }
  }, 500)
  const changeSwitch = async (val) => {
    let data = {
      limit: 0,
      name: val,
      page: 0,
    }
    if (createCode.type == 1) {
      await productPageSelect(data).then((res) => {
        if (res.data.code == 20000) {
          options.value = res.data.data.rows
          loading2.value = false
          createCode.codeVos[0].options = options.value
        } else {
          ElMessage({
            showClose: true,
            message: res.data.message,
            type: 'error',
            duration: 5000,
            plain: true,
          })
        }
      })
    } else {
      await sparePageSelect(data).then((res) => {
        if (res.data.code == 20000) {
          options.value = res.data.data.rows
          loading2.value = false
          createCode.codeVos[0].options = options.value
        } else {
          ElMessage({
            showClose: true,
            message: res.data.message,
            type: 'error',
            duration: 5000,
            plain: true,
          })
        }
      })
    }
  }
  const chaneSelect = async (index, id, val) => {
    optId2.value = id
    optIndex.value = index
    createCode.codeVos[index].goodsSpecId = null
    createCode.codeVos[index].options2 = null
    let data = {
      limit: 0,
      name: val,
      page: 0,
    }
    if (!id) {
      return
    }
    if (createCode.type == 1) {
      await productSpecPageSelect(data, id).then((res) => {
        if (res.data.code == 20000) {
          options2.value = res.data.data.rows
        } else {
          ElMessage({
            showClose: true,
            message: res.data.message,
            type: 'error',
            duration: 5000,
            plain: true,
          })
        }
        loading3.value = false
      })
    } else {
      await spareSpecPageSelect(data, id).then((res) => {
        if (res.data.code == 20000) {
          options2.value = res.data.data.rows
        } else {
          ElMessage({
            showClose: true,
            message: res.data.message,
            type: 'error',
            duration: 5000,
            plain: true,
          })
        }
        loading3.value = false
      })
    }
    createCode.codeVos[index].options2 = options2.value
  }

  // 保存
  const saveLoading = ref(false)
  const onaddSave = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid) => {
      if (valid) {
        let data = _.cloneDeep(createCode)
        data.codeVos = data.codeVos.map((o) => {
          delete o.options
          delete o.options2
          return o
        })
        let goodsId = data.codeVos.some((o) => {
          return !o.goodsId
        })
        let goodsSpecId = data.codeVos.some((o) => {
          return !o.goodsSpecId
        })
        if (goodsId) {
          ElMessage({
            showClose: true,
            message: '请选择产品型号',
            type: 'error',
            duration: 5000,
            plain: true,
          })
          return
        }
        if (goodsSpecId) {
          ElMessage({
            showClose: true,
            message: '请选择产品规格',
            type: 'error',
            duration: 5000,
            plain: true,
          })
          return
        }

        saveLoading.value = true
        addSave(data).then((res) => {
          if (res.data.code == 20000) {
            saveLoading.value = false
            ElMessage({
              showClose: true,
              message: res.data.message,
              type: 'success',
              duration: 5000,
              plain: true,
            })
            createCode.name = ''
            createCode.qty = 1
            createCode.type = 1
            createCode.codeVos = [
              {
                goodsId: null, //产品ID
                goodsSpecId: null, //产品规格ID
                qty: '1', //生成条码数量
                warrantyDay: ' 1', //质保周期/天数
                options: [],
                options2: [],
              },
            ]
            onClose()
            emits('update')
          } else {
            ElMessage({
              showClose: true,
              message: res.data.message,
              type: 'error',
              duration: 5000,
              plain: true,
            })
          }
        })
      }
    })
  }

  const visible = ref(false)
  const onClose = () => {
    visible.value = false
    createCode.codeVos = [
      {
        goodsId: null, //产品ID
        goodsSpecId: null, //产品规格ID
        qty: '1', //生成条码数量
        warrantyDay: ' 1', //质保周期/天数
        options: [],
        options2: [],
      },
    ]
    createCode.name = '' //批次名称
    createCode.qty = 1 //条码数量
    createCode.type = 1 //条码类型：1-成品、2-物料
    emits('update:modelValue', visible.value)
  }

  watch(
    () => createCode.type,
    () => {
      createCode.codeVos = [
        {
          goodsId: null, //产品ID
          goodsSpecId: null, //产品规格ID
          qty: '1', //生成条码数量
          warrantyDay: ' 1', //质保周期/天数
          options: null,
          options2: null,
        },
      ]
    },
  )

  watch(
    props,
    (value) => {
      visible.value = value.modelValue
      getDepartmentOptions()
    },
    { immediate: true, deep: true },
  )

  onMounted(() => {
    changeSwitch('')
  })
</script>
<style lang="scss" scoped>
  @import './index.scss';
</style>
